<?php

namespace Frieza\Modules\Evaluation\Controllers;

use Illuminate\Support\MessageBag;
use App\Http\Controllers\Controller;
use App\Pockets\GridDataModel as pGridDataModel;
use App\Admin\Extensions\Tools\UserButton;
use Encore\Admin\Facades\Admin;
use Encore\Admin\Grid;
use Encore\Admin\Layout\Content;
use Encore\Admin\Widgets\Form;
use Encore\Admin\Widgets\Tab;
use Illuminate\Http\Request;
use Doraemon\model\Category;
use Doraemon\model\Evaluation\H5EvaluateForm;
use Doraemon\tools\ImgUrl;
use Doraemon\model\Evaluation\Evaluation as mEvaluation;
use Doraemon\service\Evaluation\Evaluation as sEvaluation;
use Doraemon\model\Evaluation\ReportRelateEvaluation as mReportRelateEvaluation;
use Doraemon\model\Evaluation\H5EvaluateFormData;
use Doraemon\cache\UserCounter;
use Doraemon\service\BadgeService;
use Doraemon\pockets\excel\DownExcel;
use Doraemon\model\Article;
use Doraemon\model\Blank;
use Doraemon\model\Member;

class EvaluationController extends Controller
{
    const PAGE_SIZE = 50;

    public function list(Content $content,Request $request)
    {
        $params = [
            'page'              => $request->input('page', 1),
            'per_page'          => $request->input('per_page', 20),
            'title'             => $request->input('title', ''),
            'status'            => $request->input('status', ''),
        ];
        return $content
            ->header('测评管理')
            ->breadcrumb(
                ['text' => '测评管理列表', 'url' => '/admin/evaluation/list']
            )
            ->body($this->listAction($params));
    }

    private function listAction($params = [])
    {
        $info = sEvaluation::getList($params);
        $gridModel = new pGridDataModel($info['data'],$info['total'],[
            'perPage' => $params['per_page'],
        ]);

        $listGrid = Admin::grid($gridModel, function (Grid $grid) {
            $grid->disableExport();
            $grid->disableRowSelector();
            $grid->disableCreateButton();
            // 操作
            $grid->actions(function ($actions) {
               
            });
            // 筛选项
            $grid->filter(function (Grid\Filter $filter) {
                $filter->disableIdFilter();
                $filter->equal('title', '标题')->placeholder('请输入标题');
                $filter->in('status', '活动状态')->radio(mEvaluation::FILTER_STATUS);
            });
            $grid->column('id');
            $grid->column('title', '标题')->display(function(){
                return $this->title."<br />".'数量：'.$this->head_count;
            });
            $grid->column('activity_status', '活动状态');
            $grid->column('applyNums', '申请表单')->display(function($applyNums){
                return "提交数据：<a href='http://form-admin.haohaozhu.me/form/dataList?id={$this->form_id}'>$applyNums</a><br/>用户信息：<a href='/admin/evaluation/list/download/{$this->form_id}' ele.target='_blank'>用户信息</a>";
            });
            
            $grid->column('is_top', '是否置顶')->switch($this->makeStatus(mEvaluation::IS_TOP_ON, mEvaluation::IS_TOP_OFF));

            $grid->column('status', '是否发布（否为下架）')->switch($this->makeStatus(mEvaluation::STATUS_PUBLISH, mEvaluation::STATUS_UNPUBLISH));
            $grid->column('is_list_commit')->hide();
            $grid->column('show_tab', '是否默认展示测评报告Tab')
            ->switch($this->makeStatus(mEvaluation::SHOW_ON, mEvaluation::SHOW_OFF));
            
            $grid->column('realyNums', '真实参与人数');
            $grid->column('countOfOld', '美化参与人数')->editable();
            $grid->column('addNum', '总人数')->display(function(){
                return $this->realyNums+$this->countOfOld;
            });
            $grid->column('date', '时间')->display(function($date){
                
                return '<dl class="">
                            <dt>开始时间:</dt><dd>'.$date['start_time'].'</dd>
                            <dt>结束时间:</dt><dd>'.$date['end_time'].'</dd>
                            <dt>公布时间:</dt><dd>'.$date['publish_result_time'].'</dd>
                        </dl>
                        ';
            });
            $grid->column('link', '内容预览')->urlWrapper();
        });

        return $listGrid->render();
    }

    public function edit($id=0, Request $request, Content $content)
    {
        $tab = new Tab();
        $tab->add('测评编辑', $this->editAction($id));
        if ($id > 0) {
            // 检测活动状态 
            $info = mEvaluation::getInfoById($id, '*');
            $nowTime = time();
            // 活动结束后才能编辑发布获奖名单  发布获奖名单之后 才能公布测评报告  之后显示测评报告的tab
            if ($info['end_time'] < $nowTime) {
                $tab->add("获奖名单", $this->applyListAction($id, $info));
                if ($nowTime > $info['publish_result_time'] && $info['is_publish_list'] == 1) {
                    $tab->add("测评报告", $this->reportListAction($id));
                }
            }
        }
        
        return $content
            ->header('测评管理')
            ->breadcrumb(
                [
                    'text' => '测评管理列表',
                    'url'  => '/evaluation/list'
                ],
                ['text' => "测评编辑"]
            )
            ->body($tab);
    }

    private function editAction($id = 0)
    {
        $forms = H5EvaluateForm::getFormList();
        //$form_options = [];
        if ($id > 0) {
            $info = sEvaluation::getInfoByIdForForm($id, '*');
            $form = new Form($info);
            $form->hidden('id', $id);
        } else {
            $form = new Form();
            
        }
        $form->imgUpload('head_pic_id', '头图', false, ['imgType' => ImgUrl::APPTYPE_APP, 'imgSize' => ImgUrl::IMAGE_SIZE_ORI_NPHONE])
        ->help('请上传750*375头图 上传图片大小请勿超过300k,小方图为100k');
        $form->videoUpload('video_url', '头部视频地址')
        ->help('请在设置-视频上传管理中上传视频，并获取地址(50M以内)');
        $form->text('title', '标题')->required();
        $form->text('wiki_id', 'wiki_id');
        $form->number('head_count', '名额')->width('1000');
        $form->text('market_price', '市场价')
        ->placeholder('￥4')
        ->required()
        ->help('所见即所得，如需说明人民币，需要自行填写￥');
        $form->text('brand_uid', '品牌uid')
        ->help('只能填写一个uid');

        $form->divider();
        $form->select('form_id', '选择测评表单')->options($forms)->load('note_relate_remark', 'getOptions');

        $form->text('note_relate_tag', '发note关联标签')->help('若此测评支持发note,则可选填此项,词语间用英文逗号分隔，无需加#号');
        $form->text('note_relate_pre_remark', '发note图说前缀文案')->help('若此测评支持发note,则必填填此项');
        $form->divider();

        $form->datetime('start_time', '开始时间')
        ->required()->help('仅可精确到小时');
        $form->datetime('end_time', '结束时间')->required()->help('仅可精确到小时');
        $form->date('publish_result_time', '活动结果公布时间')->required();
        $form->textarea('join_rule', '参与规则')->required();
        $form->ckEditor('content', '正文')->required();
        $form->imgUpload('share_img', '分享头图', false, ['imgType' => ImgUrl::APPTYPE_APP, 'imgSize' => ImgUrl::IMAGE_SIZE_ORI_NPHONE]);
        $form->text('share_title', '分享标题')->required();
        $form->text('share_desc', '分享描述')->required();
        $form->action('/admin/evaluation/list/save');

        return $form;
    }

    public function getOptions(Request $request)
    {
        $request = $request->all();
        return H5EvaluateForm::getOptionList($request['q']);
    }

    private function applyListAction($id, $info)
    {
        $info = sEvaluation::applyList($id);

        $gridModel = new pGridDataModel($info);

        $listGrid = Admin::grid($gridModel, function (Grid $grid)use($id) {
            $grid->disableExport();
            $grid->disableRowSelector();
            $grid->disablePagination();
            $grid->disableFilter();
            
            $grid->tools(function ($tools)use($id) {
                // 检测活动状态 
                $info = mEvaluation::getInfoById($id, '*');
                $nowTime = time();
                //  发布获奖名单之后 才能公布测评报告  之后显示测评报告的tab
                if ($nowTime > $info['publish_result_time']) {
                    $tools->append("<a href='publishList' class='btn btn-sm btn-success' style='float: right;'>
<i class='fa fa-flag'>&nbsp;&nbsp;公布名单</i></a>");
                } else {
                    $tools->append("<p class='btn btn-sm btn-success' style='float: right;'>
<i class='fa fa-flag'>&nbsp;&nbsp;未到公布时间</i></p>");
                }
            });

            // 操作
            $grid->actions(function ($actions) {
                // 去掉编辑
                $actions->disableEdit();

                // 去掉查看
                $actions->disableView();
            });

            $grid->column('uid');
            $grid->column('nick', '呢称');
            $grid->column('in_apply', '是否在申请表单');
            
        });

        return $listGrid->render();
    }

    private function reportListAction($id)
    {
        $info = sEvaluation::getMultiReportRelateEvaluation($id);
        $gridModel = new pGridDataModel($info);
        $listGrid = Admin::grid($gridModel, function (Grid $grid) {
            $grid->disableExport();
            $grid->disableRowSelector();
            $grid->disablePagination();
            $grid->disableFilter();
            $grid->disableActions();
            $grid->disableCreateButton();

            $grid->column('nick', '用户');
            $grid->column('title', '文章')->display(function(){
                return $this->obj_id."<br />".$this->title;
            });
            $grid->column('publish_time', '首发时间');
            $grid->column('status', '是否发布')->switch($this->makeStatus(mReportRelateEvaluation::STATUS_PUBLISH, mReportRelateEvaluation::STATUS_UNPUBLISH));;
        });

        return $listGrid->render();
    }

    public function editApplyUser($id=0, Request $request, Content $content)
    {
        $tab = new Tab();
        $title = '添加获奖人员';
        
        $tab->add($title, $this->createApplyUser($id));
        return $content
            ->header('测评管理')
            ->breadcrumb(
                [
                    'text' => '测评管理列表',
                    'url'  => '/evaluation/list'
                ],
                [
                    'text' => '测评管理修改',
                    'url'  => "/evaluation/list/{$id}/edit"
                ],
                ['text' => "$title"]
            )
            ->body($tab);
    }

    private function createApplyUser($evaluation_id = 0)
    {
        $form = new Form();
        $form->text('uids','uid')->required('请输入用户uid');

        $form->action("/admin/evaluation/list/applyuser/add/{$evaluation_id}");
        return $form->render();
    }


    public function listSave(Request $request)
    {
        $params = $request->all();
        $result = sEvaluation::listSave($params);
        if (!is_string($result)) {
            $success = new MessageBag([
                'title' => '操作成功'
            ]);
            return redirect('/admin/evaluation/list')->with(compact('success'));
        } else {
            return back()->with('error', new MessageBag([
                'title' => $result
            ]));
        }
    }
    public function delApplyUser($evaluation_id, $id, Request $request)
    {
        $result = sEvaluation::delapplyUser($id, $evaluation_id);
        if ($result) {
            return response()->json([
                'status' => true,
                'message' => "修改成功",
            ]);
        } else {
            return response()->json([
                'status' => false,
                'message' => "修改失败",
            ]);
        }
        
    }

    public function addApplyUser($evaluation_id, Request $request)
    {
        $uid = $request->input('uids','');
        $result = sEvaluation::addApplyUser($evaluation_id,$uid);
        if ($result['code']) {
            $success = new MessageBag([
                'title' =>  '操作成功'
            ]);
            return redirect("/admin/evaluation/list/{$evaluation_id}/edit")->with(compact('success'));
        } else {
            return back()->with('error', new MessageBag([
                'title' => $result['message'],
            ]));
        }
    }
    /**
     * 生成开关
     */
   private static function makeStatus($on = 1, $off = 9)
   {
        $status = [
            'on' => [
                'value' => $on,
                'text' => '是'
            ],
            'off' => [
                'value' => $off,
                'text' => '否'
            ],
        ];

        return $status;
   }

   /**
    * 更改 是否置顶	是否下架 是否展示测评报告的状态
    */
   public function updateStatus($id, Request $request)
   {
        $params = $request->all();
        if (isset($params['is_top']) && $params['is_top'] == 'on') {
            $isTop = mEvaluation::getCount(['is_top'=>mEvaluation::IS_TOP_ON,'status' => mEvaluation::ADMIN_NORMAL]);
            if ($isTop) {
                return response()->json([
                    'status' => false,
                    'message' => "已存在置顶活动",
                ]);
            }
        }
        if (isset($params['show_tab']) && $params['show_tab'] == 'on') {
            $isShowTab = mEvaluation::getCount(['is_list_commit'=>mEvaluation::IS_LIST_COMMIT_OFF,'status' => mEvaluation::ADMIN_NORMAL,'id'=>$id]);
            if ($isShowTab) {
                return response()->json([
                    'status' => false,
                    'message' => "后台没有公布报告",
                ]);
            }
        }
        $result = sEvaluation::updateStatus($id, $params);
        if ($result) {
            return response()->json([
                'status' => true,
                'message' => "操作成功",
            ]);
        }else {
            return response()->json([
                'status' => false,
                'message' => "操作失败",
            ]);
        }
        
   }


   public function downExcel($id)
   {
       $result = sEvaluation::downExcel($id);

       if ($result['code']) {
        return back()->with('success', new MessageBag([
            'title' => $result['message']
        ]));
       }else {
        return back()->with('error', new MessageBag([
            'title' => $result['message']
        ]));
       }
   }

   public function reportPublishStatus($evaluation_id, $id, Request $request)
   {
        $params = $request->all();
        $result = sEvaluation::reportPublishStatus($evaluation_id, $id, $params);

        if ($result) {
            return response()->json([
                'status' => true,
                'message' => "操作成功",
            ]);
        }else {
            return response()->json([
                'status' => false,
                'message' => "操作失败",
            ]);
        }
   }

   // 公布获奖名单
   public function publishList($evaluation_id)
   {
        $result = sEvaluation::publishList($evaluation_id);
        if ($result['code']) {
            return back()->with('success', new MessageBag([
                'title' => '操作成功'
            ]));
        } else {
            return back()->with('error', new MessageBag([
                'title' => $result['message']
            ]));
        }

   }

   /**
    * 
    */
   public function reportPublish($evaluation_id, $id, Request $request)
   {
       $status = $request->input('status', '');
       if ($status == 'on') {
            $result = sEvaluation::reportPublish($evaluation_id, $id);
       } else {
            $result = sEvaluation::cancel_report_publish($evaluation_id, $id); 
       }
       
        if ($result['code']) {
            return response()->json([
                'status' => true,
                'message' => "操作成功",
            ]);
        }else {
            return response()->json([
                'status' => false,
                'message' => "操作失败",
            ]);
        }
   }

   public function delEvalution($id)
   {
        $result = sEvaluation::delEvalution($id); 

        if ($result) {
            return response()->json([
                'status' => true,
                'message' => "操作成功",
            ]);
        }else {
            return response()->json([
                'status' => false,
                'message' => "操作失败",
            ]);
        }
    }

    //下载表单
    public function downLoadExcel($form_id)
    {
        $answer_infos = H5EvaluateFormData::getAnswersByFormId($form_id);
        //组合表头
        $header_base = ['用户id', '用户昵称', '图片数', '整屋数', '文章数', '回答数', '粉丝数', '获赞与收藏','用户徽章'];
        $uids = array_column($answer_infos, 'uid');
        //图片数、整屋数、文章数、回答数、粉丝数、获赞与收藏、用户身份、用户徽章
        $rs = [];
        if($uids && is_array($uids)) {
            $uids = array_unique(array_filter($uids));
            $user_counts = UserCounter::getMulti($uids);
            $user_badges = BadgeService::listAllBadgeName($uids);
            $user_infos = Member::getUsers($uids);
            foreach($uids as $uid) {
                $count['article'] = (int)Article::getPublishCountByUid($uid);
                $count['blank'] = (int)Blank::getPublishCountByUid($uid);
                $rs[$uid][] = $uid;
                $rs[$uid][] = $user_infos[$uid]['nick'];
                $rs[$uid][] = (int) $user_counts[$uid]['photo'];
                $rs[$uid][] = (int) $count['article'];
                $rs[$uid][] = (int) $count['blank'];
                $rs[$uid][] = (int) $user_counts[$uid]['answer'];
                $rs[$uid][] = (int) $user_counts[$uid]['fans'];
                $rs[$uid][] = (int) $user_counts[$uid]['beliked'] + (int) $user_counts[$uid]['befavorite'];
                $rs[$uid][] = (string) implode(',', (array)$user_badges[$uid]);
            }
        }
        $DownExcel = new DownExcel();
        //表头加粗
        $DownExcel->setFrontBold('1');
        $title = "用户信息表";
        //设置文件名
        $DownExcel->setFileName($title);
        //设置标题
        $DownExcel->setTitle($title);
        $DownExcel->setSheetTitle($title);
        //创建excel
        $DownExcel->create(array_values($rs), $header_base);
        return back()->with('success', new MessageBag([
            'title' => '下载成功'
        ]));
    }
}
